<template>
  <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="closeDialog"
      width="600px"
  >
    <div class="brand-relation-container">
      <!-- 左侧选择区域 -->
      <div class="select-category">
        <div class="select-title">新增分类关联</div>
        <el-cascader
            v-model="value"
            :options="options"
            :props="props"
            @change="handleChange"
            placeholder="请选择分类"
            filterable
            clearable
        >
        </el-cascader>
      </div>

      <!-- 右侧已关联列表 -->
      <div class="relation-list">
        <div class="list-title">已关联分类</div>
        <div v-if="cateList.length > 0" class="cate-list">
          <el-table :data="cateList" style="width: 100%" size="small" border>
            <el-table-column
                prop="catelogId"
                label="分类ID"
                width="120"
                align="center"
            >
            </el-table-column>
            <el-table-column prop="catelogName" label="分类名称" align="center">
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope.row)"
                >
                  解除关联
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="empty-text">暂无关联分类</div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      title: '',
      props: {
        value: 'catId',
        label: 'name',
        children: 'children',
      },
      value: [],
      options: [],
      visible: false,
      cateList: [],
      brandId: null, // 保存当前品牌ID
    }
  },
  methods: {
    closeDialog () {
      this.value = []
    },
    findCategoryNameById (categories, catId) {
      for (const category of categories) {
        if (category.catId === catId) {
          return category.name
        }
        if (category.children && category.children.length > 0) {
          const result = this.findCategoryNameById(category.children, catId)
          if (result) {
            return result
          }
        }
      }
      return null // 如果没有找到，返回null
    },
    handleChange (value) {
      if (!value || value.length === 0) return

      console.log('value:', this.options)
      console.log('选择的分类:', value)
      let catelogId = value[value.length - 1]
      let catelogName = this.findCategoryNameById(this.options, catelogId)
      console.log('最后一级分类ID:', catelogId)
      console.log('最后一级分类名称:', catelogName)

      if (catelogId && catelogName) {
        this.insertCateList(catelogId, catelogName)
      }
    },
    insertCateList (catelogId, catelogName) {
      console.log('brandId:', this.brandId)
      console.log('brandName:', this.brandName)
      console.log('catelogId:', catelogId)
      console.log('catelogName:', catelogName)
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/categorybrandrelation/save'),
        method: 'post',
        data: this.$http.adornData({
          brandId: this.brandId,
          catelogId: catelogId,
          catelogName: catelogName,
          brandName: this.brandName,
        }),
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message.success('关联成功')
          this.fetchCateList(this.brandId)
          this.value= []
        } else {
          console.log(data)
        }
      })
    },
    getMenus () {
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/category/list/tree'),
        method: 'get',
      }).then(({data}) => {
        this.options = data.data
      })
    },
    fetchCateList (id) {
      this.$http({
        url: this.$http.adornUrl(
            `/gulimailproduct/categorybrandrelation/getListByBrandId/${id}`
        ),
        method: 'get',
      }).then(({data}) => {
        this.cateList = data.list.map((item) => ({
          catelogId: item.catelogId,
          catelogName: item.catelogName,
        }))
      })
    },
    init (id, name) {
      this.brandId = id
      this.title = `品牌【${name}】关联分类`
      this.visible = true
      this.brandName = name
      this.fetchCateList(id)
    },
    // 解除关联
    handleDelete (row) {
      this.$confirm(`是否解除与分类【${row.catelogName}】的关联？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(
              '/gulimailproduct/categorybrandrelation/deleteByBrandIdAndCateId'
          ),
          method: 'post',
          data: this.$http.adornData({
            brandId: this.brandId,
            catelogId: row.catelogId,
          }),
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('解除关联成功')
            this.fetchCateList(this.brandId)
          } else {
            console.log(data)
          }
        })
      })
    },
    // 表单提交
    dataFormSubmit () {
      // if (!this.value || this.value.length === 0) {
      //   this.$message.warning("请选择要关联的分类");
      //   return;
      // }

      // // 获取最后一级分类ID
      // const categoryId = this.value[this.value.length - 1];

      // this.$http({
      //   url: this.$http.adornUrl("/gulimailproduct/categorybrandrelation/save"),
      //   method: "post",
      //   data: this.$http.adornData({
      //     brandId: this.brandId,
      //     catelogId: categoryId,
      //   }),
      // }).then(({ data }) => {
      //   if (data && data.code === 0) {
      //     this.$message.success("关联成功");
      //     this.fetchCateList(this.brandId);
      //     this.value = []; // 清空选择
      //   } else {
      //     this.$message.error(data.msg || "关联失败");
      //   }
      // });
      this.visible = false
    },
  },
  created () {
    this.getMenus()
  },
}
</script>

<style scoped>
.brand-relation-container {
  padding: 20px;
}

.select-category {
  margin-bottom: 30px;
}

.select-title,
.list-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
  font-weight: bold;
}

.relation-list {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.cate-list {
  margin-top: 15px;
}

.empty-text {
  color: #909399;
  text-align: center;
  margin: 20px 0;
}

/* 级联选择器样式 */
.el-cascader {
  width: 100%;
}

/* 表格内按钮样式 */
.el-button--text {
  color: #ff4949;
}

.el-button--text:hover {
  color: #ff6d6d;
}
</style>
